/* 
 * File:   Responser.h
 * Author: faraj
 *
 * Created on October 4, 2009, 8:42 PM
 */

#include "Client.h"
#include "GlobalData.h"
#include "NOTIFICATION.h"
#include <vector>

#ifndef _RESPONSER_H
#define	_RESPONSER_H

static bool response_help(Client *cli, vector<string> *args)
{
    cout << COMMAND_HELP << " from " << *cli->getAddress()->getAddress() <<endl;
    cli->sendText(getHelpCommand());
    return true;
}

static bool response_version(Client *cli, vector<string> *args)
{
    cout << COMMAND_VERSION << " from " << *cli->getAddress()->getAddress() <<endl;
    cli->sendText(getVersion());
    return true;
}

static bool response_quit(Client *cli, vector<string> *args)
{
    cout << COMMAND_QUIT << " from " << *cli->getAddress()->getAddress() <<endl;
    cli->sendText("\ngood bye");
    cli->sendText(NOTIFY_QUIT);
    clientList.removeClient(cli);
    return true;
}


static bool response_put(Client *cli, vector<string> *args)
{
    cli->sendText(NOTIFY_FILE_PUT);
    string ssize = args->operator [](2);
    int size = atoi(ssize.c_str());
    string filename = args->operator [](1);
    
    cout << "recieving file " << filename << " (" << size << " bytes)" << endl;
    
   
    File *file = cli->getFile(filename,size);
    if(file == NULL)
    {
        cli->sendText(NOTIFY_FILE_PUT_ERROR);
        return false;
    }
    fileList.setFile(file);
    string msg = NOTIFY_FILE_PUT_DONE;
    msg += " ";
    msg += file->getHash();
    cli->sendText(msg);
    return true;
}


static bool response_get(Client *cli, vector<string> *args)
{
    string hash = args->operator [](1);
    
    File *file = fileList.getFile(hash);
    
    
    if(file != NULL)
    {
        int size = getFileSize(file->getPath());
        char *ssize = new char[10];
        sprintf(ssize,"%i",size);
        cout << "recieving file " << file->getPath() << " (" << size << " bytes)" << endl;
        
        string msg = NOTIFY_FILE_GET;
        msg += " ";
        msg += file->getPath();
        msg += " ";
        msg += ssize;
                
        cout << msg;
        cli->sendText(msg);
        
        cli->sendFile(file);
        
        cli->sendText(NOTIFY_FILE_GET_DONE);
    }
    else
    {
        cli->sendText(NOTIFY_FILE_GET_ERROR);
    }
}

static bool response_del(Client *cli, vector<string> *args)
{
    string hash = args->operator [](1);
    
    File *file = fileList.getFile(hash);
    
    if(file != NULL)
    {
        
        if(file->deleteFile() && fileList.deleteFile(hash))
        {
            cli->sendText("file deleted");
            return true;
        }
        else
        {
            cli->sendText("file delete error");
            return false;
        }
    }
    cli->sendText("file cannot be located");
    return false;
}
#endif	/* _RESPONSER_H */

